﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using static System.Net.Mime.MediaTypeNames;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ProfileVisa")]
	public class ProfileVisaController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ProfileContributeInfoModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = from conferenceAttendenceInfo in DbContext.ConferenceAttendenceInfo.AsNoTracking()
					.Where(x => x.Creator == LoginUser.UserName)
				  join conferenceMaster in DbContext.ConferenceMaster.AsNoTracking()
					on conferenceAttendenceInfo.ConferenceId equals conferenceMaster.ID
				  join visaInfo in DbContext.VisaInfo.AsNoTracking()
					on conferenceAttendenceInfo.ID equals visaInfo.AttendenceId into visas
				  from visa in visas.DefaultIfEmpty()
				  select new
				  {
					  conferenceId = conferenceMaster.ID,
                                          conferenceName = conferenceMaster.ConferenceName,
					  status = visa != null ? visa.Status : ConstValues.InvitationStatus.未申请,
					  sendStatus = visa != null ? visa.SendStatus : (ConstValues.strHyphen + ConstValues.strHyphen),
					  conferenceAttendId = conferenceAttendenceInfo.ID,
					  fullName = conferenceAttendenceInfo.FullName,
					  ConferenceNickName = conferenceMaster.ConferenceNickName,
					  HomePageUrl = conferenceMaster.HomePageUrl,
					  CreateDate = conferenceAttendenceInfo.CreateDate,
				  };

			if (!string.IsNullOrWhiteSpace(model.queryConferenceName) && model.queryConferenceName != "")
			{
				sql = sql.Where(x => x.conferenceName.Contains(model.queryConferenceName));
			}

			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.CreateDate).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			return JsonCamelCase(new
			{
				Total = total,
				Rows = sqlResult,
			},
			JsonRequestBehavior.AllowGet);
		}

		[Route("GetInvoiceUserData")]
		public async Task<JsonCamelCaseResult> GetInvoiceUserData(string attendId)
		{
			var sqlResult = await DbContext.VisaInfo.AsNoTracking().FirstOrDefaultAsync(x => x.AttendenceId == attendId);

			if (sqlResult == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
			var result = new
			{
				familyName = sqlResult.FamilyName,
				firstName = sqlResult.FirstName,
				title = DbContext.TitleMaster.AsNoTracking().FirstOrDefault(x => x.ID == sqlResult.Title)?.ID,
				affiliation = sqlResult.Affiliation,
				address = sqlResult.Address,
				country = DbContext.LocationMaster.AsNoTracking().FirstOrDefault(x => x.ID == sqlResult.Country)?.ID,
				state = sqlResult.StateStr,
				city = sqlResult.CityStr,
				zipCode = sqlResult.ZipCode,
				mail = sqlResult.Mail,
				tele = sqlResult.Telephone,
				birthday = Utility.SetDate(sqlResult.Birthdate, Request.Cookies["_culture"].Value),
				gender = sqlResult.Gender,
				passportNum = sqlResult.PassportNum,
				issueOfCountry = sqlResult.IssueOfCountry,
				dateOfIssue = Utility.SetDate(sqlResult.DateOfIssue, Request.Cookies["_culture"].Value),
				expiryDate = Utility.SetDate(sqlResult.ExpiryDate, Request.Cookies["_culture"].Value),
				arrivalDate = Utility.SetDate(sqlResult.ArrivalDate, Request.Cookies["_culture"].Value),
				departuralDate = Utility.SetDate(sqlResult.DeparturalDate, Request.Cookies["_culture"].Value),
				remark = sqlResult.Remark,
			};

			return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
					JsonRequestBehavior.AllowGet);
		}

		[Route("SaveData")]
		public async Task<JsonResult> SaveData(ProfileVisaModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			using (var transaction = DbContext.Database.BeginTransaction())
			{
				var user = await DbContext.VisaInfo.FirstOrDefaultAsync(x => x.AttendenceId == model.AttendenceId);

				if (user == null)
				{
					var visaInfo = new VisaInfo
					{
						ID = Utility.GetTableId(ConstValues.TableName.VisaInfo),
						ConferenceId = model.ConferenceId,
						AttendenceId = model.AttendenceId,
						FamilyName = string.IsNullOrEmpty(model.FamilyName) ? string.Empty : model.FamilyName?.Trim(),
						FirstName = string.IsNullOrEmpty(model.FirstName) ? string.Empty : model.FirstName?.Trim(),
						FullName = Utility.SetFullName(model.FamilyName?.Trim(), model.FirstName?.Trim(),
								Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En ?
									ConstValues.Language.En : ConstValues.Language.Cn),
						StateStr = model.State,
						Telephone = model.Telephone?.Trim(),
						Title = model.Title,
						ZipCode = model.ZipCode?.Trim(),
						Address = model.Address?.Trim(),
						CityStr = model.City,
						Country = model.Country,
						Gender = model.Gender == "Female" ? false : true,
						PassportNum = model.PassportNum,
						IssueOfCountry = model.CountryOfIssue,
						ArrivalDate = model.ArrivalDate,
						DeparturalDate = model.DeparturalDate,
						DateOfIssue = model.IssueDate,
						ExpiryDate = model.ExpiryDate,
						Mail = model.Mail,
						Affiliation = model.Affiliation,
						Remark = model.Remark,
						Birthdate = model.Birthday,
						Creator = LoginUser.UserName,
						CreateDate = DateTime.Now,
						CreateIP = LoginUser.IP,
						Status = ConstValues.InvitationStatus.已申请,
						SendStatus = ConstValues.SendStatus.未发送,
					};

					DbContext.VisaInfo.Add(visaInfo);
				}
				else
				{
					user.FamilyName = string.IsNullOrEmpty(model.FamilyName) ? string.Empty : model.FamilyName?.Trim();
					user.FirstName = string.IsNullOrEmpty(model.FirstName) ? string.Empty : model.FirstName?.Trim();
					user.Affiliation = model.Affiliation?.Trim();
					user.Mail = model.Mail?.Trim();
					user.Telephone = model.Telephone?.Trim();
					user.Title = model.Title;
					user.ZipCode = model.ZipCode?.Trim();
					user.Address = model.Address?.Trim();
					user.Birthdate = model.Birthday;
					user.CityStr = model.City;
					user.Country = model.Country;
					user.StateStr = model.State;
					user.Gender = model.Gender == "Female" ? false : true;
					user.PassportNum = model.PassportNum;
					user.IssueOfCountry = model.CountryOfIssue;
					user.DateOfIssue = model.IssueDate;
					user.ExpiryDate = model.ExpiryDate;
					user.ArrivalDate = model.ArrivalDate;
					user.DeparturalDate = model.DeparturalDate;

					user.Updater = LoginUser.UserName;
					user.UpdateDate = DateTime.Now;
					user.UpdateIP = LoginUser.IP;
				}
				var attendInfo = await DbContext.ConferenceAttendenceInfo.FirstOrDefaultAsync(x => x.ID == model.AttendenceId);
				attendInfo.HasVisa = true;
				attendInfo.Updater = LoginUser.UserName;
				attendInfo.UpdateDate = DateTime.Now;
				attendInfo.UpdateIP = LoginUser.IP;

				await DbContext.SaveChangesAsync();
				transaction.Commit();
			}

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit), JsonRequestBehavior.AllowGet);
		}

		[Route("DownloadInvitation")]
		public async Task<ActionResult> DownloadInvitation(string conferenceAttendId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var user = await DbContext.VisaInfo.AsNoTracking()
					.FirstOrDefaultAsync(x => x.AttendenceId == conferenceAttendId);

			if (user != null && !string.IsNullOrEmpty(user.Invitation))
			{
				return File(user.Invitation, Application.Octet, Path.GetFileName(user.Invitation));
			}
			else
			{
				return new HttpStatusCodeResult(HttpStatusCode.NotFound);
			}
		}
	}
}